<template>
  <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="关键字" prop="prjName">
            <el-input v-model="queryParams.prjName" placeholder="项目名称/标准号" clearable size="small" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <!-- <el-form-item label="标准类型" prop="standardType">
            <el-select v-model="queryParams.standardType" placeholder="请选择" clearable size="small">
              <el-option v-for="dict in typeStandardLevelOptions" :key="dict.dictLabel" :label="dict.dictLabel" :value="dict.dictLabel" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="审核单位" prop="auditCompany">
            <el-select v-model="queryParams.auditCompany" placeholder="请选择" clearable size="small">
              <el-option v-for="dict in typeStandardUnitOptions" :key="dict.dictLabel" :label="dict.dictLabel" :value="dict.dictLabel" />
            </el-select>
          </el-form-item>

          <el-form-item label="经办人" prop="operatorName">
            <el-input v-model="queryParams.operatorName" placeholder="请输入关键字" clearable size="small" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="编制单位" prop="editCompany">
            <el-input v-model="queryParams.editCompany" placeholder="请输入关键字" clearable size="small" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="办理人" prop="currOptName">
            <el-input v-model="queryParams.currOptName" placeholder="请输入关键字" clearable size="small" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="开始时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="当前状态" prop="processStatus">
            <el-select v-model="queryParams.processStatus" placeholder="请选择" clearable size="small">
              <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
            <el-button size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
    </el-form>
    <el-row :gutter="20" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          :disabled="(roles.indexOf('admin')==-1)"
          @click="handleAdd"
          v-hasPermi="['standard:reexamine:add']"
        >新增</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['standard:reexamine:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['standard:reexamine:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['standard:reexamine:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reexamineList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="left" />-->
      <el-table-column label="项目名称" align="left" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span >{{ scope.row.projectName }}（{{ scope.row.standardNo }}）</span>
        </template>
      </el-table-column>
      <el-table-column label="经办人" align="left" prop="userName" width="120" />
      <el-table-column label="单位名称" align="left" prop="deptName" />
      <el-table-column label="当前办理人" align="left" prop="flowTo" />
      <el-table-column label="开始时间" align="left" prop="stmp" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.stmp) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status">
        <template slot-scope="scope">
          <!-- <span>{{scope.row.statusCn}}</span>
          <el-progress :percentage="scope.row.status" status="success" v-if="scope.row.wStatus=='3'"></el-progress>
          <el-progress :percentage="scope.row.status" v-if="scope.row.wStatus=='2'"></el-progress>
          <el-progress :percentage="scope.row.status" status="exception" v-if="scope.row.wStatus=='1'"></el-progress>
          <el-progress :percentage="scope.row.status" status="warning" v-if="scope.row.wStatus=='0'"></el-progress> -->
          <div class="status_box">
            <div :class="['status_icon',scope.row.wStatus=='0' ? 'warning_bg' : (scope.row.wStatus=='1' ? 'danger_bg' : scope.row.wStatus=='2' ? 'primary_bg' : scope.row.wStatus=='3' ? 'success_bg' : '')]"></div>
            <div>{{scope.row.statusCn}}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)">详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            v-if="((scope.row.flowToName.split(',').indexOf(userName)>=0)||roles.indexOf('admin')!=-1) && scope.row.wStatus!='3'"
            @click="handleTransact(scope.row)"
            v-hasPermi="['standard:reexamine:edit']">办理
          </el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['standard:reexamine:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="(scope.row.wStatus=='0' && scope.row.flowToName.split(',').indexOf(userName)>=0)||roles.indexOf('admin')!=-1"
            @click="handleDelete(scope.row)"
            v-hasPermi="['standard:reexamine:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标准规范复审对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
          <el-card class="box-card">

            <div slot="header" class="clearfix">
              <span style="font-size: 16px;font-weight: 600;">项目基础信息</span>
            </div>
            <el-form ref="prjForm" :model="prjForm" :rules="rules" label-width="120px">
              <el-row>
                <
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectName">
                    <el-select style="width: 380px;" v-model="prjForm.projectName" placeholder="" @change="handleSelectPrj" :disabled="prjSelect" >
                      <el-option v-for="prj in projectList" :key="prj.nid" :label="prj.projectName" :value="prj.nid" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12" v-if=" hasPrjInfo ">
                  <el-form-item label="关键词" prop="keyword">
                    <el-input v-model="prjForm.keyword" placeholder="" readonly />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if=" hasPrjInfo ">
                <el-col :span="12">
                  <el-form-item label="专业门类选择" prop="majorValue">
                    <el-cascader style="width: 380px;" v-model='majorValue' :options="majorOptions" placeholder="" disabled></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="功能序列选择" prop="functionValue">
                    <el-cascader style="width: 380px;" v-model='functionValue' :options="functionOptions" placeholder=""
                      disabled></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="标准性质" prop="standardNature">
                    <el-select style="width: 380px;" v-model="prjForm.standardNature" placeholder="" disabled>
                      <el-option v-for="dict in typeStandardNatureOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="标准状态" prop="standardStatus">
                    <el-select style="width: 380px;" v-model="prjForm.standardStatus" placeholder="" disabled>
                      <el-option v-for="dict in typeStandardStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目负责人" prop="pi">
                    <el-input v-model="prjForm.pi" placeholder="" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="职务" prop="post">
                    <el-input v-model="prjForm.post" placeholder="" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话" prop="tel">
                    <el-input v-model="prjForm.tel" placeholder="" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电子邮件" prop="email">
                    <el-input v-model="prjForm.email" placeholder="" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="制定或修订" prop="tp">
                    <el-radio-group v-model="prjForm.tp" size="small" disabled>
                      <el-radio-button label="制定"></el-radio-button>
                      <el-radio-button label="修订"></el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
           </el-card>

           <el-card class="box-card" style="margin-top: 20px;">
             <div slot="header" class="clearfix">
               <span style="font-size: 16px;font-weight: 600;">审批处附件</span>
               <SPAN class="text-info" >（只能上传word/pdf/png/jpg/jpeg文件，且不超过20M）</SPAN>
             </div>
             <el-form ref="form" :model="form" :rules="rules" label-width="120px">

               <el-row>
                 <el-col :span="12">
                   <el-form-item label="修改意见" prop="files">
                     <el-upload
                       ref="upload"
                       accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
                       :headers="upload.headers"
                       action="#"
                       :disabled="fileEditDisabled"
                       :on-change="handleCheckFile"
                       :on-preview="handleViewFile"
                       :on-remove="handleRemoveFile"
                       :http-request="requestUpload"
                       :before-upload="beforeUpload"
                       :before-remove="beforeRemoveFile"
                       :auto-upload="autoUpload"
                       :file-list="fileList"
                        >
                       <el-button size="small" icon="el-icon-upload2" :disabled="fileEditDisabled">点击上传</el-button>
                       <!-- <div class="el-upload__tip" slot="tip" >提示：只能上传word/pdf/png/jpg文件，且不超过20M！</div> -->
                     </el-upload>
                   </el-form-item>
                 </el-col>
               </el-row>
             </el-form>
           </el-card>


          <div slot="footer" class="dialog-footer" v-if="!viewOpt">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="handleFlowToNextStep" v-if="optPage">流程结束</el-button>
            <el-button type="primary" @click="submitForm" v-if="!optPage">保 存</el-button>
          </div>

          <!-- 开始办理对话框 -->
          <el-dialog title="开始办理" :visible.sync="openOpt" width="650px" append-to-body>
            <el-form ref="formOpt" :model="formOpt" label-width="100px">
              <el-row>
                <el-col :span="16">
                  <el-form-item label="办理人意见" >
                    <el-input v-model="myOpinion" type="textarea" rows="5" placeholder=""></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8" class="word_hui">
                  <el-button size="small" style="margin-top: 3px;margin-left: 10px;" @click="inputOpinion">同意。</el-button>
                  <el-button size="small" style="margin-top: 3px;" @click="inputOpinion">已阅。</el-button>
                  <el-button size="small" style="margin-top: 3px;" @click="inputOpinion">退回。</el-button>
                  <el-button size="small" style="margin-top: 3px;" @click="inputOpinion">抓紧办理。</el-button>
                  <el-button size="small" style="margin-top: 3px;" @click="inputOpinion">重新修改。</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="流程提交至">
                    <el-select v-model="submitTo" value-key="dictValue" placeholder="请选择" @change="handleCheckedFlowTo">
                      <el-option v-for="dict in flowToOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="flowToLabel!='流程结束'">
                <el-col :span="24">
                  <el-form-item :label="flowToLabel">
                    <el-select v-model="submitToName" value-key="userId" placeholder="请选择" ><!-- @change="handleCheckedFlowToName" 暂时没用上 -->
                      <el-option v-for="user in flowToNameOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="openOpt = false">返 回</el-button>
              <el-button type="primary" @click="submitOptForm">办理完成</el-button>
            </div>
          </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  listReexamine,
  getReexamine,
  delReexamine,
  addReexamine,
  updateReexamine,
  exportReexamine,
  addUploadFile,
  updateUploadFile,
  delUploadFile,
  getUploadFiles,
  selectPrjOptions
 } from "@/api/standard/reexamine";

import {
    getNotice

  } from '@/api/standard/notice'

import {
  optionSelect
} from "@/api/system/dict/data"

import {
  getToken
} from "@/utils/auth";
// 默认流程
import flowToDefault from "@/utils/flowToDefault";

import {
  getFlow,
  selectOptions,
  saveFlow,
  listOpinion
} from "@/api/standard/flow";

import store from "@/store";

export default {
  name: "Reexamine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标准规范评估表格数据
      reexamineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: null,
        prjName: null,
        processStatus: null,
        operatorName: null,
        currOptName: null,
        standardType: null,
        auditCompany: null,
        editCompany: null,

      },

      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userid: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        nid: [
          { required: true, message: "项目唯一标识id不能为空", trigger: "blur" }
        ],
        wid: [
          { required: true, message: "工作流节点id不能为空", trigger: "blur" }
        ],
      },

      //==================================== private start ====================================
      // 判断新增、或者修改
      sid: null,

      //专业门类选择
      majorValue: [],
      majorOptions: [],
      //功能序列选择
      functionValue: [],
      functionOptions: [],
      // 类型数据字典
      typeOptions: [],
      typeStandardNatureOptions: [],
      typeStandardStatusOptions: [],
      typeStandardLevelOptions: [],
      typeStandardUnitOptions: [],

      //项目基本信息部门
      projectList: [],
      prjForm: {},
      hasPrjInfo: false,

      // 办理表单参数
      formOpt: {},
      openOpt: false,
      optPage: false,
      viewOpt: false,
      myOpinion: '',
      submitTo: "",
      submitToName: "",
      flowToLabel: "",
      opinionList: [],
      options: [],
      value: '',
      // 上传多附件时,只执行一次
      fileIndex: 0,
      // 用作页面展示的上传文件list
      fileList: [],
      // 用作上传到后台的file参数
      uploadfileList: [],
      // 控制项目下拉是否可选
      prjSelect: false,
      // 记录附件是否发生变化
      fileChange: false,
      // 被删除的文件名称
      delFileName: null,
      // 新上传的附件数量
      countNewFile: 0,

      // 是否允许编辑附件
      fileEditDisabled: false,
      // 是否自动上传
      autoUpload: false,

      // 当前用户名
      userName: store.getters && store.getters.name,
      roles: store.getters && store.getters.roles,

      // 流程节点
      flowToOptions: [],
      flowToNameOptions: [],
      // 默认流程节点
      defaultFlowToList: flowToDefault,
      // 附件上传
      upload: {
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/standard/reexamine/attachment"
      },
      //==================================== private end ====================================


    };
  },
  created() {
    this.getList();
    //立项通知流程状态
    this.getDicts('standard_notice_type').then(response => {
      this.typeOptions = response.data
    });
    //标准性质
    this.getDicts('standard_nature_type').then(response => {
      this.typeStandardNatureOptions = response.data
    });
    //标准状态
    this.getDicts('standard_status_type').then(response => {
      this.typeStandardStatusOptions = response.data
    });
    //专业门类选择
    optionSelect("standard_major_type").then(response => {
      this.majorOptions = this.cascaderNormalizer(response.data)
    });
    //功能序列选择
    optionSelect("standard_function_type").then(response => {
      this.functionOptions = this.cascaderNormalizer(response.data)
    });
    //当前用户部门的已经立项的项目列表w_status=3,且自己是经办人
    selectPrjOptions().then(response => {
      this.projectList = response.data
    });

  },

  mounted() {
    const nid = this.$route.query.nid;
    const operatType = this.$route.query.operatType;
    var row = null;
    // console.log(nid)
    if(nid!=null){
      console.log(this.total)
      for(var i=0;i<this.total;i++){
        var row_nid = this.reexamineList[i].nid;
        if(row_nid==nid){
          row = this.reexamineList[i];
          break;
        }
      }
      // console.log(row)
      if(operatType!=null&&operatType=='view'&&row!=null){
        this.handleView(row);
      }
    }
  },



  methods: {


    /** 查询标准规范评估列表 */
    getList() {
      this.loading = true;
      listReexamine(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.reexamineList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 默认打开
        const nid = this.$route.query.nid;
        if(nid!=null&&!this.askFromIndex){//false的时候才执行，变成true这个方法就不执行了
          this.askFromIndex = true;
          this.openPageFromIndex();
        }
      });
    },
   // 从首页点击办理/查看，默认打开页面
   openPageFromIndex() {
     const nid = this.$route.query.nid;
     const operatType = this.$route.query.operatType;
     var row = null;
     // console.log(nid)
     if(nid!=null){
       // console.log(this.total)
       for(var i=0;i<this.total;i++){
         var row_nid = this.reexamineList[i].nid;
         if(row_nid==nid){
           row = this.reexamineList[i];
           break;
         }
       }
       // console.log(row)
       if(operatType!=null&&operatType=='view'&&row!=null){
         this.handleView(row);
       }else if(operatType=='handle'&&row!=null){
         this.handleTransact(row)
       }
     }
   },



    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sid: null,
        userid: null,
        nid: null,
        wid: null,
        proposal: null,
        wStatus: "0",
        stmp: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetPrj()

      this.sid = null
      this.prjSelect = false

      // 清空附件列表
      this.fileList = []
      this.uploadfileList = []
      // 记录附件是否发生变更
      this.fileChange = false
      // 文件游标
      this.fileIndex = 0
      // 新增附件数
      this.countNewFile = 0

      this.autoUpload = false
      this.fileEditDisabled = false

      this.viewOpt = false
      this.optPage = false

      this.open = true;
      this.title = "添加标准规范评估";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sid = row.sid || this.ids
      getReexamine(sid).then(response => {
        this.form = response.data;
        this.title = "修改标准规范评估";
      });

      this.sid = sid
      // 这个参数获取需要时间,先从row里面拿到，避免getFlow的参数为空报错
      this.form.wid = row.wid
      this.form.sid = sid
      this.form.nid = row.nid
      this.form.userid = row.userid


      // 项目编码
      const nid = row.nid
      this.handleSelectPrj(nid);
      // 是否办理页面
      this.optPage = false
      // 下拉框控制不能修改
      this.prjSelect = true

      // 清空附件列表
      this.fileList = []
      this.uploadfileList = []
      // 记录附件是否发生变更
      this.fileChange = false
      // 文件游标
      this.fileIndex = 0
      // 新增附件数
      this.countNewFile = 0

      // 自动上传文件
      this.autoUpload = true
      // 是否允许编辑文件
      this.fileEditDisabled = false

      this.viewOpt = false
      // 加载附件
      getUploadFiles(sid).then(response => {
        for(var i=0;i<response.data.length;i++){
          var img = {}
          img.name = response.data[i].fname
          img.url = process.env.VUE_APP_BASE_API + response.data[i].filename
          this.fileList.push(img)
        }
      });


      this.open = true;

    },


    /** 提交按钮 */
    submitForm() {
      if (this.prjForm == null || this.prjForm.nid == null) {
        this.msgError("请选择一个项目！");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sid != null) {
            console.log("updateReexaminer开始保存...")
            updateReexamine(this.form).then(response => {
              // 上传附件
              if(this.fileChange){// 附件发生变化
                this.$refs.upload.submit();//调用requestUpload方法
              }
              this.msgSuccess('保存成功')
              this.open = false
            });
          } else {
            //赋值起草人信息
            console.log("addReexaminer开始保存...")
            this.form.nid = this.prjForm.nid;
            addReexamine(this.form).then(response => {
              // 上传附件
              const sid = response.sid;
              this.form.sid = sid;
              this.sid = sid;
               if(sid!=null){
                  if(this.fileChange){// 附件发生变化
                    this.$refs.upload.submit();//调用requestUpload方法
                  }

                  this.msgSuccess('保存成功')
                  this.getList()
                  this.open = false
                }
            });
          }
        }
      });
    },



        /** 删除按钮操作 */
        handleDelete(row) {
          const sids = row.sid || this.ids;
          this.$confirm('是否确认删除标准规范评估编号为"' + sids + '"的数据项?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              return delReexamine(sids);
            }).then(() => {
              this.getList();
              this.msgSuccess("删除成功");
            })
        },
        /** 导出按钮操作 */
        handleExport() {
          const queryParams = this.queryParams;
          this.$confirm('是否确认导出所有标准规范评估数据项?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              return exportReexamine(queryParams);
            }).then(response => {
              this.download(response.msg);
            })
        },




    //==================================== private start ==================================
    resetPrj() {
      this.hasPrjInfo = false
      this.majorValue = null
      this.functionValue = null

      this.prjForm = {
        projectName: null,
        keyword: null,
        standardNature: null,
        standardStatus: null,
        pi: null,
        post: null,
        tel: null,
        email: null,
        tp: null,
        nid: null
      };
      this.resetForm("prjForm");
    },

    resetOptForm() {
      this.formOpt = {
        id: null,
        nid: null,
        stamp: null,
        userid: null,
        opt: null,
        ctn: null,
        res: null,
        opn: null,
        flowToUserid: null,
        flowToRoleid: null,
        flowToDeptid: null,
        currNodeK: null,
        currNode: null,
        nextNodeK: null,
        nextNode: null
      };
      this.resetForm("formOpt");
    },

    /** 查看操作 */
    handleView(row){
      this.reset();
      const sid = row.sid || this.ids
      this.sid = sid
      this.form.wid = row.wid
      this.form.sid = sid
      this.form.nid = row.nid
      this.form.userid = row.userid


      getReexamine(sid).then(response => {
        console.log(response.data)
        this.form = response.data;

        this.title = '查看标准规范评估'
      });

      // 项目编码
      const nid = row.nid
      this.handleSelectPrj(nid);
      // 是否办理页面
      this.optPage = true
      // 查看标记
      this.viewOpt = true
      // 下拉框控制不能修改
      this.prjSelect = true

      // 清空附件列表
      this.fileList = []
      this.uploadfileList = []
      // 记录附件是否发生变更
      this.fileChange = false
      // 文件游标
      this.fileIndex = 0
      // 新增附件数
      this.countNewFile = 0

      // 自动上传文件
      this.autoUpload = true
      // 是否允许编辑文件
      this.fileEditDisabled = true

      // 加载附件
      getUploadFiles(sid).then(response => {
        for(var i=0;i<response.data.length;i++){
          var img = {}
          img.name = response.data[i].fname
          img.url = process.env.VUE_APP_BASE_API + response.data[i].filename
          this.fileList.push(img)
        }
      });

      //加载办理意见列表
      this.opinionInfos();

      this.open = true
    },

    // 根据选中的角色,查找相应的用户清单
    handleCheckedFlowTo(value) {
      // console.log("handleCheckedFlowTo:")
      this.submitToName = null
      this.flowToNameOptions = []

      if (value == 'end') {
        this.flowToLabel = "流程结束"
        return false
      }

      const userid = this.formOpt.userid
      // console.log(this.formOpt)
      selectOptions(userid, value).then(response => {
        this.flowToNameOptions = response.data
        // 默认选择第一个
        if (this.flowToNameOptions.length>0) {
          this.submitToName = this.flowToNameOptions[0].userId
        }

        if (value == 'operator') { // 经办人
           //注意this.form.userid为空会使userid丢失
           this.submitToName = this.form.userid
           this.formOpt.userid = this.submitToName
        }
      });

      let obj = this.flowToOptions.find((item) => { //这里的carslist就是上面遍历的数据源
        return item.dictValue === value; //筛选出匹配数据
      });
      // console.log(obj); //obj即是选中的Option数据集合
      //获取到选中的Option数据集并进行其它操作
      this.flowToLabel = obj.dictLabel
    },

    /** 选中人员 */
    handleCheckedFlowToName(value) {
      //console.log(value)
      this.formOpt.userid = value
    },
    // 开始办理
    handleOpinion() {
      if(this.fileList.length==0){
        this.$message.error('附件为空，请先修改后再办理');
        return false;
      }
      this.openOpt = true;
    },
    inputOpinion(value) {
      this.myOpinion += value.srcElement.innerText;
    },

    /** 办理完成提交按钮 */
    submitOptForm() {
      // 遇到bug Textarea无法用validate，这个表单验证漏洞百出，屌用都没有，只能自己写
      if(this.myOpinion==null||this.myOpinion==''){
        this.$message.error('办理人意见不能为空');
        return false
      }else{
        // 设置当前节点办理意见
        this.formOpt.opn = this.myOpinion;
      }
      if(this.submitTo==null||this.submitTo==''){
        this.$message.error('请选择流程跳转至');
        return false
      }else{
        // 设置节点提交后的办理人角色名称+角色编码
        this.formOpt.currNodeK = this.submitTo
        this.formOpt.currNode = this.flowToLabel
      }
      if(this.flowToLabel!='流程结束'&&(this.submitToName==null||this.submitToName=='')){
        this.$message.error('办理人不能为空');
        return false
      }else{
        // 设置节点提交后办理人ID
        this.formOpt.userid = this.submitToName
      }

      if(this.flowToLabel=='流程结束'){
        if (this.fileList.length <= 0) {
          this.msgError("请至少上传一个标准规范报审稿！");
          return;
        }
      }

      // 补全参数(默认值)
      this.formOpt.flowToDeptid = null
      this.formOpt.flowToUserid = null
      this.formOpt.flowToRoleid = null
      this.formOpt.nextNode = null
      this.formOpt.nextNodeK = null

      // 根据下拉this.flowToOptions自动获取nextNode和nextNodeK
      var olen = this.flowToOptions.length
      const currNodeK = this.formOpt.currNodeK;
      if(currNodeK!='end'){
        for(var i=0;i<olen;i++){
          var obj = this.flowToOptions[i];//dictLabel   dictValue
          if(currNodeK==this.flowToOptions[i].dictValue){
            this.formOpt.nextNodeK = this.flowToOptions[i+1].dictValue
            this.formOpt.nextNode = this.flowToOptions[i+1].dictLabel
            break;
          }
        }
      }



      // 保存办理意见，流程跳转
      if (this.formOpt.nid != null) {
        saveFlow(this.formOpt).then(response => {
          console.log(response)
          //根据两个参数，修改技术委员会审议状态（由页面发起请求，修改状态流程状态）
          var wid = response.wid;
          this.updateWstatus(wid)
        });
      }
    },

    //更新当前审批的W_STATUS和WID(0待办，1退回，2办理中，3流程结束)
    updateWstatus(wid){
      this.form.wid = wid;
      var CurrNodeK = this.formOpt.currNodeK
      var status = this.getFlowStatus(CurrNodeK)
      this.form.wStatus = status
      if (this.form.sid != null) {
        updateReexamine(this.form).then(response => {
          this.msgSuccess("提交成功");
          this.open = false;
          this.openOpt = false
          this.getList();
        });
      }
    },

    /*
    // 根据当前节点key获取状态值（审批处专用）
    getFlowStatusJsc(CurrNodeK) {
      var status = '1'
      if (CurrNodeK=='end') {//完成
        status = '3'
      }else {//办理中
        status = '2'
      }
      return status
    },
    */



    /** 提交部门审核 */
    handleFlowTo() {
      const nids = this.ids
      this.$confirm('确认立项通知信息无误并提交部门负责人审核?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        // return delNotice(nids)
      }).then(() => {
        this.getList()
        this.msgSuccess('提交成功')
        this.open = false
      })
    },

    /* 流程技术 */
    handleFlowToNextStep() {
      if (this.fileList.length <= 0) {
        this.msgError("无标修改意见，请修改上传后办理！");
        return;
      }

      const confirmText = ['确认实施材料无误并结束流程？',  '如有缺漏，请修改上传后办理~']
      const newDatas = []
      const h = this.$createElement
      for (const i in confirmText) {
        newDatas.push(h('p', null, confirmText[i]))
      }
      const nids = this.ids
      this.$confirm('提示', {
        title: '提示',
        message: h('div', null, newDatas),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 进入下一个环节时,先赋值，再调用已有方法submitOptForm
        this.myOpinion = '流程结束'
        this.submitTo = 'end'
        this.flowToLabel = '流程结束'
        this.submitOptForm()
      })
    },



    // 办理按钮操作
    handleTransact(row) {


      this.reset();

      // 这一步很必要
      const sid = row.sid || this.ids
      this.sid = sid
      // 这个参数获取需要时间,先从row里面拿到，避免getFlow的参数为空报错
      this.form.wid = row.wid
      this.form.sid = sid
      this.form.nid = row.nid
      this.form.userid = row.userid
      getReexamine(sid).then(response => {
        // console.log(response.data)
        this.form = response.data;
        this.title = '办理标准规范评估'
      });

      // 项目编码
      const nid = row.nid

      this.handleSelectPrj(nid);
      // 是否办理页面
      this.optPage = true
      // 下拉框控制不能修改
      this.prjSelect = true



      // 清空附件列表
      this.fileList = []
      this.uploadfileList = []
      // 记录附件是否发生变更
      this.fileChange = false
      // 文件游标
      this.fileIndex = 0
      // 新增附件数
      this.countNewFile = 0

      // 自动上传文件
      this.autoUpload = true
      // 是否允许编辑文件
      this.fileEditDisabled = false
      this.viewOpt = false
      // 加载附件
      getUploadFiles(sid).then(response => {
        for(var i=0;i<response.data.length;i++){
          var img = {}
          img.name = response.data[i].fname
          img.url = process.env.VUE_APP_BASE_API + response.data[i].filename
          this.fileList.push(img)
        }
      });

      //加载办理意见列表
      this.opinionInfos();

      this.open = true
    },

    // 加载办理页面表单信息
    pageOpinion() {
      // 重置开始办理表单（写在这里方便记录未完成的意见）
      this.myOpinion = ""
      this.submitTo = ""
      this.submitToName = ""
      this.flowToLabel = ""

      // 根据部门名称,从字典查询配置好的流程（技术委员会专有流程）
      /*
      this.getDicts('std_process_jswyh').then(response => {
        this.flowToOptions = response.data
        if(this.flowToOptions.length==0){
          this.flowToOptions = this.defaultFlowToList
        }
      });
      */
      // 根据部门名称,从字典查询配置好的流程
      this.getDictsByName(this.prjForm.eunit).then(response => {
        this.flowToOptions = response.data
        if(this.flowToOptions.length==0){
          this.flowToOptions = this.defaultFlowToList
        }
      });


      // 根据wid获取流程信息，并设置默认流程节点+人
      const id = this.form.wid

      getFlow(id).then(response => {
        // console.log(response.data)
        this.formOpt = response.data

        // 根据角色+部门获取人员列表
        const nextNodeK = this.formOpt.nextNodeK
        // 默认选择中流程
        this.submitTo = nextNodeK
        this.flowToLabel = this.formOpt.nextNode
        const userid = this.formOpt.userid
        // console.log(userid)
        selectOptions(userid, nextNodeK).then(response => {
          this.flowToNameOptions = response.data
          // 默认选择第一个
          if (this.flowToNameOptions.length>0) {
            this.submitToName = this.flowToNameOptions[0].userId
          }
        });

      });
    },
    // 审批意见列表
    opinionInfos(){
      var tableName = 'tb_reexamine'
      listOpinion(this.form.nid,tableName).then(response => {
        this.opinionList = response.data
      });
    },


    handleSelectPrj(value) {
      this.hasPrjInfo = true
      // 根据选择的nid查询详情
      getNotice(value).then(response => {
        this.functionValue = response.data.functionValue == null ? [] : response.data.functionValue.split(",").map(
          Number);
        this.majorValue = response.data.majorValue == null ? [] : response.data.majorValue.split(",").map(Number);
        this.selfEvlaOpt = response.data.selfEvla == null ? [] : response.data.selfEvla.split(",").map(String);
        this.prjForm = response.data

        // 先取项目资料，再根据部门取流程资料(只有办理页面才需要加载)
        if(this.optPage){
          this.pageOpinion();
        }

        // this.open = true
      })
    },
    // 上传预处理
    beforeUpload(file) {
      console.log("beforeUpload...")
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["pdf", "doc", "docx", "jpg", "jpeg", "png"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.msgError("上传文件只能是 pdf、doc、docx、jpg、jpeg、png格式", "error");
        return false;
      }
      const isLt20M = (file.size / 1024 / 1024) < 20;
      if (!isLt20M) {
        this.msgError("上传文件大小不能超过 20MB", "error");
        return false;
      }
      console.log("- 文件大小格式符合通过...")
    },

    // 覆盖默认的上传行为（每个附件都会执行一次）
    requestUpload(value) {
      console.log("start upload...")
      let formData = new FormData();
      // 将附件循环赋值给后台参数uploadfileList[]
      this.uploadfileList[this.fileIndex++] = value.file

      if(this.countNewFile==this.uploadfileList.length){
        for(var i=0;i<this.uploadfileList.length;i++){
          formData.append("files", this.uploadfileList[i]);
        }
        // formData.append("nid", this.prjForm.nid);//项目ID
        this.form.nid = this.prjForm.nid
        formData.append("data", JSON.stringify(this.form));
        if (this.sid != null) {
          formData.append("sid", this.sid);//起草id
          console.log("- update")
          updateUploadFile(formData).then(response => {

            const len = this.fileList.length
            if(len>0&&this.autoUpload){//将文件状态改为success
              this.fileList[len-1].status = 'success'
            }
            this.uploadfileList = []
            this.fileChange = false
            this.fileIndex = 0
            this.countNewFile = 0
            // this.getList()
            if(!this.autoUpload){
              // this.$refs.upload.clearFiles();
              // this.fileList = []
              // this.open = false
            }else{
              this.msgSuccess("提交成功");
            }

          });
        }
        console.log("- 附件上传成功！")
      }
    },
    // 选中文件，list+1
    handleCheckFile(file, fileList) {
      this.fileList = fileList
      this.fileChange = true
      // 新增1个文件
      this.countNewFile++
    },
    // 查看附件
    handleViewFile(file, fileList){
      window.open(file.url)
    },
    // 删除附件
    handleRemoveFile(file, fileList){
      // 此处是被移除的file和fileList
      // 单独写一个移除方法,fileChange只有新上传了文件才改变
      this.fileChange = false
      // 判断是否已经上传到服务器的文件
      if(file.status=='success'){
        // 被移除附件名称
        console.log("删除文件："+file.url)
        let formData = new FormData();
        formData.append("fileName", file.url);//附件名称
        delUploadFile(formData).then(response => {
          console.log(response)
        });
      }else{
        this.countNewFile--
      }
    },
    beforeRemoveFile(file, fileList) {
      if(this.optPage&&this.fileEditDisabled){
        this.msgError("办理中不能删除附件！");
        return false;
      }
      return this.$confirm(`确定移除 ${ file.name }吗，移除后不能恢复？`);
    },
    // 文件上传中处理(添加requestUpload不起作用)
    handleFileUploadProgress(event, file, fileList) {
      console.log("handleFileUploadProgress...")
    },
    // 文件上传成功处理(添加requestUpload不起作用)
    handleFileSuccess(response, file, fileList) {
      console.log("handleFileSuccess")
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "提交结果", {
        dangerouslyUseHTMLString: true
      });
      //this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      console.log("提交...")
      if (this.prjForm == null || this.prjForm.nid == null) {
        this.msgError("请选择一个项目！");
        return;
      }
      if (this.fileList.length <= 0) {
        this.msgError("请至少上传一个文件！");
        return;
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.fileChange){// 附件发生变化
            this.$refs.upload.submit();//调用requestUpload方法
          }else{//当附件没有变化时，仅更新对内容
            updateReexamine(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });

          }
        }
      });
    },

    /* 追加实施材料 */
    handleAdditional(row){
      this.reset();
      const sid = row.sid || this.ids
      getReexamine(sid).then(response => {
        this.form = response.data;

        this.title = "标准规范评估";
      });

      this.sid = sid
      // 这个参数获取需要时间,先从row里面拿到，避免getFlow的参数为空报错
      this.form.wid = row.wid
      this.form.sid = sid
      this.form.nid = row.nid
      this.form.userid = row.userid

      // 项目编码
      const nid = row.nid
      this.handleSelectPrj(nid);
      // 是否办理页面
      this.optPage = false
      // 下拉框控制不能修改
      this.prjSelect = true
      // 清空附件列表
      this.fileList = []
      this.uploadfileList = []
      // 记录附件是否发生变更
      this.fileChange = false
      // 文件游标
      this.fileIndex = 0
      // 新增附件数
      this.countNewFile = 0

      this.fileEditDisabled = false;
      this.autoUpload = true

      this.viewOpt = false
      // 加载附件
      getUploadFiles(sid).then(response => {
        for(var i=0;i<response.data.length;i++){
          var img = {}
          img.name = response.data[i].fname
          img.url = process.env.VUE_APP_BASE_API + response.data[i].filename
          this.fileList.push(img)
        }
      });

      this.open = true;
    }

    //==================================== private end ====================================












  }
};
</script>
